<?php
namespace app\bbs\controller;
class Tie extends Base
{
    //社区首页
    public function init(){
        $uid = $this->get('uid');
        session('uid', $uid);
        #发帖英雄榜
        $user = $this->db->query('select * from user where status=0 order by id desc limit 12');
        #置顶
        $sql = "
            select
                a.*,b.is_rz,b.pic,b.username,b.level,c.cat_title
            from
                tie a
            left join
                user b
            on
                a.user_id=b.id
            left join
                tie_cat c
            on
                a.cat_id=c.id
            where
                a.is_zd=1
            order by id desc
            limit 4
        ";
        $zd = $this->db->query($sql);
        #首页帖子
        $sql = "
            select
                a.*,b.is_rz,b.pic,b.username,b.level,c.cat_title
            from
                tie a
            left join
                user b
            on
                a.user_id=b.id
            left join
                tie_cat c
            on
                a.cat_id=c.id
            where
                a.is_zd=0
            order by id desc
            limit 12
        ";
        $list = $this->db->query($sql);
        //官方群
        $rs = m('patch','c')->getData(['qun']);
        $d = [
            'cid'=>'all',
            'title' => '社区首页',
            'zd' => $zd,
            'list' => $list,
            'user' => $user,
            'qun'  => $rs['qun'],
            'sub_user' => 0, //下级会员个数
            'my_xiangmu' => [], //我的项目
        ];
        if($this->userinfo){
          //下级会员
          $map = [['and','s_tree','like', "{$this->userinfo['s_tree']}{$this->userinfo['id']},%"]];
          $w = where($map);
          $rs = $this->db->query("select count(*) as sub_user from user $w[0]",$w[1],1);
          $d['sub_user'] = $rs['sub_user'];

          //已购买项目
          $rs = $this->db->query("select concat(xiangmu_id) as types from user_xiangmu where status=0 and user_id=? and end_time>?", [$this->userinfo['id'], time()],1);
          $d['my_xiangmu'] = isset($rs['types']) ? explode(',',$rs['types']) : [];
        }
        //项目列表
        $d['xiangmu'] = $this->db->query("select * from xiangmu where status=0 order by sort desc, id desc");

        $this->fetch($d);
    }

    //论坛列表
    public function lists(){
        $cid  = $this->get('cid');
        $type = $this->get('type');
        $page = $this->get('page',1);
        $limit = $this->get('limit',20);
        $map = [];
        if($cid!='all' && $cid!=''){
            $map[] = ['and', 'a.cat_id', '=', $cid];
        }
        switch ($type) {
            case 'cn':
                $map[] = ['and', 'a.is_cn', '=', 1];
                break;
            case 'uncn':
                $map[] = ['and', 'a.is_cn', '=', 0];
                break;
            case 'jh':
                $map[] = ['and', 'a.is_jh', '=', 1];
                break;
        }
        $w = where($map);
        $sql = "
            select
                a.*,b.is_rz,b.pic,b.username,b.level,c.cat_title
            from
                tie a
            left join
                user b
            on
                a.user_id=b.id
            left join
                tie_cat c
            on
                a.cat_id=c.id
            $w[0]
            order by id desc
        ".limit($page,$limit);
        $rs =  $this->db->query($sql, $w[1],'',true);
        $d = [
            'title'=> '列表',
            'cid'  => $cid,
            'type' => $type,
            'list' => $rs[0],
            'page_count' => $rs[1],
            'page' => $page,
        ];
        $this->fetch($d);
    }

    //发帖
    public function add()
    {
        $this->checkLogin();
        if(is_post()){
            $d = $this->post;
            $rule = [
                'cat_id'  => 'require',
                'title'   => 'require',
                'content' => 'require',
            ];
            $msg = [
                'content.require'=>'内容不能为空',
            ];
            check($rule,$msg,$d);
            $d['content'] = $this->_html($d['content']);
            $d['user_id'] = $this->userinfo['id'];
            $d['create_time'] = time();
            $id = $this->db->insert('tie',$d);
            $this->db->query('update user set tie_count=tie_count+1 where id=?',[$this->userinfo['id']]);
            m('Attachment','xcom')->imgSure('tie',$id,$d);
            cookie('js_msg','发帖成功!');
            cookie('js_url',url('tie/detail')."?id=$id");
            suc();
        }
        $d = [
            'title' => '添加',
            'cat'   => $this->db->cache('select * from tie_cat where status=0 order by sort desc, id desc'),
        ];
        $this->fetch($d);
    }

    //发帖
    public function edit()
    {
        $this->checkLogin();
        $id = $this->get('id');
        $info = $this->db->find('tie',$id);
        $this->_checkRight($info);
        if(is_post()){
            $d = $this->post;
            $rule = [
                'id'  => 'require',
                'cat_id'  => 'require',
                'title'   => 'require',
                'content' => 'require',
            ];
            $msg = [
                'content.require'=>'内容不能为空',
            ];
            check($rule,$msg,$d);
            $d['content'] = $this->_html($d['content']);
            $d['update_time'] = time();
            $this->db->update('tie',$d);
            m('Attachment','xcom')->imgSure('tie',$d['id'],$d);
            cookie('js_msg','编辑成功!');
            cookie('js_url',url('tie/detail')."?id={$d['id']}");
            suc();
        }
        $d = [
            'title' => '编辑',
            'cat'   => $this->db->cache('select * from tie_cat where status=0 order by sort desc, id desc'),
            'info'  => $info,
        ];
        $this->fetch($d);
    }

    //详情
    public function detail(){
        $id = $this->get('id',1);
        $page = $this->get('page',1);
        $limit = $this->get('limit',12);

        #帖子信息
        $sql = "
            select
                a.*,b.is_rz,b.pic,b.username,b.level,c.cat_title
            from
                tie a
            left join
                user b
            on
                a.user_id=b.id
            left join
                tie_cat c
            on
                a.cat_id=c.id
            where a.id=?";
        $info = $this->db->query($sql,[$id],1);
        #查看加1
        $this->db->update('tie',['id'=>$info['id'],'views'=>$info['views']+1]);
        #回帖信息
        $sql = "
            select
                a.*,b.is_rz,b.pic,b.username,b.level,ifnull(c.dianzan_count, 0) as dianzan_count
            from
                reply a
            left join
                user b
            on
                a.user_id=b.id
            left join
                (select count(*) as dianzan_count,table_id from dianzan where `table`='reply' group by table_id) c
            on
                a.id=c.table_id
            where
            a.tie_id=? order by a.is_cn desc,a.id desc".limit($page,$limit);
        $reply = $this->db->query($sql,[$id]);
        $dianzan = [];
        if($this->userinfo){
            $dianzan = m('dianzan','c')->userDz($this->userinfo['id'],'reply');
        }
        $is_auth_edit = $this->userinfo && ($this->userinfo['is_team']==1 || $this->userinfo['id']==$info['user_id'])?true:false;
        $is_auth_admin = $this->userinfo && $this->userinfo['is_team']?true:false;
        $d = [
            'cid' => $info['cat_id'],
            'info'=> $info,
            'reply'=> $reply,
            'dianzan' => $dianzan,
            'is_auth_edit' => $is_auth_edit,
            'is_auth_admin' => $is_auth_admin,
        ];
        //t($info);
        $this->fetch($d);
    }

    //回复
    public function reply(){
        $this->checkLogin();
        if(is_post()){
            $d = $this->post;
            $d['user_id'] = $this->userinfo['id'];
            $d['create_time'] = time();
            $this->db->query('update tie set reply_count=reply_count+1 where id=?',[$d['tie_id']]);
            $id = $this->db->insert('reply',$d);
            m('Attachment','xcom')->imgSure('reply',$id,$d);
            cookie('js_msg','回复成功!');
            cookie('js_function','reload');
            suc();
        }
    }

    //点赞评论
    public function dianzanReply(){
        $this->checkLogin();
        if(is_post()){
            $d = $this->post;
            m('dianzan','c')->dz($this->userinfo['id'],'reply',$d['id']);
            header('Content-type: application/json');
            exit(json_encode(['status'=>0]));
        }
    }

    //获取回帖内容
    public function getDa(){
        $this->isAdmin();
        if(is_post()){
            $id = $this->post('id');
            $info = $this->db->find('reply',$id);
            $d=['status'=>0,'rows'=>$info];
            header('Content-type: application/json');
            exit(json_encode($d));
        }
    }

    //更新回帖
    public function updateDa(){
        $this->isAdmin();
        if(is_post()){
            $d = $this->post;
            $d['content'] = $this->_html($d['content']);
            $d['update_time'] = time();
            $this->db->update('reply',$d);
            m('Attachment','xcom')->imgSure('reply',$d['id'],$d);

            header('Content-type: application/json');
            exit(json_encode(['status'=>0]));
        }
    }

    //删除回帖
    public function deleteDa(){
        $this->isAdmin();
        if(is_post()){
            $id = $this->post('id');
            m('reply','c')->del($id);
            header('Content-type: application/json');
            exit(json_encode(['status'=>0]));
        }
    }

    //采纳
    public function replyCn(){
        $this->checkLogin();
        if(is_post()){
            $d = $this->post;
            $reply = $this->db->find('reply',$d['id']);
            $info = $this->db->find('tie',$reply['tie_id']);
            $this->_checkRight($info);


            $this->db->query('update reply set is_cn=0 where tie_id=? and is_cn=1',[$reply['tie_id']]);
            $this->db->query('update reply set is_cn=1 where id=?',[$reply['id']]);
            $this->db->query('update tie set is_cn=1 where id=?',[$reply['tie_id']]);
            header('Content-type: application/json');
            exit(json_encode(['status'=>0]));
        }
    }

    //删除
    public function del(){
        $this->checkLogin();
        if(is_post()){
            $id = $this->post('id');
            m('Tie','c')->del($id);
            header('Content-type: application/json');
            exit(json_encode(['status'=>0]));
        }
    }
    //设置
    public function set(){
        $this->checkLogin();
        if(is_post()){
            $d = $this->post;
            $this->db->query("update tie set {$d['field']}=? where id=?",[$d['rank'],$d['id']]);
            header('Content-type: application/json');
            exit(json_encode(['status'=>0]));
        }
    }
    //设置权限
    public function _checkRight($info){
        if($this->userinfo['is_team']==0 && $info['user_id']!=$this->userinfo['id']){
            if(is_ajax()){
                err('没有权限!');
            }else{
                jump('没有权限!','',1,1);
            }
        }
    }
    //转化图片
    public function _html($content){
        // preg_match_all('/img\[(.*?)\]/i', $content, $match);
        // if(isset($match[1])){
        //     foreach($match[1] as $v){
        //         $content = str_replace("img[$v]","<img src='$v' />",$content);
        //     }
        // }
        $content = preg_replace_callback('/[\xf0-\xf7].{3}/', function($r) { return '';}, $content);
        return $content;
    }
}
